template.defaults.imports.dateFormat = function(date, format) {
	date = new Date(date);
	var map = {
		"M": date.getMonth() + 1, //月份   
		"d": date.getDate(), //日   
		"h": date.getHours(), //小时   
		"m": date.getMinutes(), //分   
		"s": date.getSeconds(), //秒   
		"q": Math.floor((date.getMonth() + 3) / 3), //季度   
		"S": date.getMilliseconds() //毫秒   
	};
	format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
		var v = map[t];
		if(v !== undefined) {
			if(all.length > 1) {
				v = '0' + v;
				v = v.substr(v.length - 2);
			}
			return v;
		} else if(t === 'y') {
			return(date.getFullYear() + '').substr(4 - all.length);
		}
		return all;
	});
	return format;
};
template.defaults.imports.timestamp = function(value) {
	return value * 1
};
var MainView = {};
var BC_Tool = {
	copyValue: function(msg, success) {
		input = document.createElement('input');
		document.body.appendChild(input);
		input.setAttribute('value', msg);
		input.select();
		if(document.execCommand('copy')) {
			document.execCommand('copy');
			success();
		}
		document.body.removeChild(input);
	},
};
MainView.ws = {
	param: null,
	talk1: function(data) {
		if(typeof data.result != "undefined" && data.result != 1) {
			AlertView.layer.msg(data.msg);
			return;
		};
		for(var i in MainView.list.data) {
			var param = MainView.list.data[i];
			if(param.gameId = data.gameId) {
				MainView.ws.param = param;
			}
		}
		if(MainView.ws.param == null) {
			AlertView.layer.msg("未找到gameId：" + data.gameId);
			return;
		}

		var index = BC_Notify.show({
			title: data.player,
			msg: "对方向您发起了挑战，是否应战？",
			timerInterval: 20,
			actions: [{
				type: "btn",
				title: "是",
				func: function() {
					MainView.ws.talk2(true);
					BC_Notify.close(index);
					AlertView.layer.loading("正在等待对方进入游戏...");
				},
			}, {
				type: "btn",
				title: "否",
				func: function() {
					MainView.ws.talk2(false);
					BC_Notify.close(index);
				},
			}]
		})
	},
	talk2: function(select, p) {
		BC_WS.send({
			player: App.accounts[0],
			gameId: MainView.ws.param.gameId,
			result: select ? 1 : 0,
			msg: select ? "应战" : "对方拒绝了您的挑战",
			cmd: "talk2",
		});
		if(select) {}
	},
	challenge: function(data, p) {
		console.log("MainView.ws.challengt " + data);
		$(".layui-layer .notify_loading .content1 ").css("background-color","white");
		if(typeof data.result != "result" && data.result != "1") {
			layer.closeAll();
			BC_Notify.show({
				msg: data.msg ? data.msg : "对方取消了挑战",
				mask: false
			});
			return;
		};
		BC_Notify.show({
			msg: data.msg ? data.msg : "挑战成功",
			mask: false
		});
		layer.closeAll();
		MainView.list.search({});
		window.open(BCConfig.url + "game.jsp?gameId=" + data.gameId, '_blank', '');
	},
	state: function(data, p) {
		layer.closeAll();
		BC_Notify.show({
			msg: data.msg,
		});
		MainView.list.search({});
		AlertView.layer.msg(data.msg);
	},
	msg: function(data, p) {
		layer.closeAll();
		BC_Notify.show({
			msg: data.msg,
		});
		MainView.list.search({});
		AlertView.layer.msg(data.msg);
	}
}
MainView.apply = {
	applyBtn: $("#applyBtn"),
	applyBtnClick: function(data) {
		MainView.apply.data = data;

		var content = AlertView.ApplyGameHtml.getHtml(data);
		AlertView.layer.open("对方已经接受了挑战", content, function() {
			AlertView.ApplyGameHtml.init(MainView.apply);
			AlertView.ApplyGameHtml.getAddrInput().val("0x" + data.gameId);
			AlertView.ApplyGameHtml.getValueInput().val(data.stake / 1000000000000000000);
			$(".layui-layer input").attr("readonly", "true");
			$(".layui-layer  select").attr("disabled", "disabled");

		}, {
			area: ['300', '180'],
			shadeClose: false
		});
	},
	submitClick: function() {
		var hashId = AlertView.ApplyGameHtml.getAddrInput().val();
		var value = AlertView.ApplyGameHtml.getValueInput().val() * 1000000000000000000;
		var index = AlertView.layer.loading("正在提交请求到链上(大约1分钟,请勿关闭)...");

		BC.getBalance().then(function(data) {
			var balance = data.toNumber();
			if(value > balance) {
				AlertView.layer.alert("错误", "您的账户余额不足");
			} else {
				BC.do("challenge", {
						hashId: hashId,
						value: value
					})
					.then(MainView.apply.result)
					.catch(MainView.apply.error);
			}
		}).catch(MainView.apply.error);
	},
	cancleSubmit: function() {
		BC_WS.send({
			cmd: "challenge",
			gameId: MainView.apply.data.gameId,
			result: 0,
			player: App.accounts[0]
		});
		layer.closeAll();
	},
	result: function(result) {
		if(result.logs.length < 1) {
			MainView.apply.error({
				code: 10,
				msg: "应战失败"
			});
			return;
		}
		$(".notify_loading .content1 .title").html("正在等待合约执行完成...");
		$(".layui-layer .notify_loading .content1 ").css("background-color","lightgray");

	},
	error: function(err) {
		AlertView.layer.alert("错误", err.msg);
		BC_WS.send({
			cmd: "challenge",
			gameId: MainView.apply.data.gameId,
			result: 0,
			player: App.accounts[0]
		});
	},
	init: function() {
		MainView.apply.applyBtn.on("click", MainView.apply.applyBtnClick);
	}
};

MainView.init = function() {
	BC_WS.addObserver("talk1", function(data, p) {
		console.log("MainView addObserver  talk1");
		MainView.ws.talk1(data);
	}, true);

	BC_WS.addObserver("challenge", function(data, p) {
		console.log("MainView addObserver challenge" + data);
		MainView.ws.challenge(data);
	}, true);

	BC_WS.addObserver("msg", function(data, p) {
		console.log("MainView addObserver msg" + data);
		MainView.ws.msg(data);
	}, true);
	BC_WS.addObserver("state", function(data, p) {
		console.log("MainView addObserver msg" + data);
		MainView.ws.state(data);
	}, true);

	MainView.create.init();
	MainView.apply.init();
	$("#searchBtn").on("click", function() {
		MainView.list.search();
	});

}